//
//  SQLiteManager.swift
//  17-FMDB演练
//
//  Created by 高伦展 on 2018/3/27.
//  Copyright © 2018年 glz. All rights reserved.
//

import Foundation

private let dbname = "readme.db"

class SQLiteManager {

    //单例
    static let shareManager = SQLiteManager()
    //全局数据库操作队列
    let queue:FMDatabaseQueue
    
    private init(){
        //0.数据库路径 - 全路径（可读可写）
        var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
        
        path = (path as NSString).appendingPathComponent(dbname)
        
        print("数据库路径：" + path)
        
        //1.打开数据库队列
        //数据库存在，打开；不存在，创建
        queue = FMDatabaseQueue(path:path)
        
        createTable()
    }
    
    //执行sql，返回字典
    func execRecordSet(sql:String) -> [[String:AnyObject]] {
        
        var result = [[String:AnyObject]]()
        
        SQLiteManager.shareManager.queue.inDatabase { (db) in
            guard let rs = db!.executeQuery(sql: sql) else{
                print("not row")
                return
            }
            
            while rs.next(){
                let colCount = rs.columnCount()
                
                var dict = [String:AnyObject]()
                
                for col in 0..<colCount{
                    let name = rs.columnName(for: col)
                    let obj = rs.object(forColumnIndex: col)
                    
                    dict[name!] = obj as AnyObject
                }
                result.append(dict)
            }
            
            print(result)
        }
        return result
    }
    
    private func createTable(){
        
        let path = Bundle.main.path(forResource: "db.sql", ofType: nil)!
        
        let sql = try! String(contentsOfFile: path)
         
        queue.inDatabase { (db) in
            if (db?.executeStatements(sql))!{
                print("创建成功")
            }else{
                print("创建失败")
            }
        }
    }
}
